package com.xuhzhiguang.youdao.cli;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class YoudaoTranslateUtils {


    private final static String URL = "https://dict.youdao.com/w/";

    private final static OkHttpClient HTTP_CLIENT = new OkHttpClient();

    public static String translate(String word) throws IOException {

        boolean isChinese = isChinese(word);


        String url = URL + URLEncoder.encode(word, StandardCharsets.UTF_8).replaceAll("\\+", "%20");

        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();

        String html = response.body().string();
        return format(html, isChinese);
    }

    private static boolean isChinese(String word) {
        String pattern = "[\\u4e00-\\u9fa5]+";
        return word.matches(pattern);
    }

    private static String format(String html, boolean isChinese) {

        StringBuilder sb = new StringBuilder();

        Document document = Jsoup.parse(html);
        Elements container = document.select("div[id='results-contents']");
        Elements phraseListTab = container.select("div[id='phrsListTab']");


        if (!phraseListTab.isEmpty()) {
            // 单词
            String keyword = phraseListTab.select("span[class='keyword']").text();
            sb.append(keyword).append("\n\n");

            // 音标
            if (!isChinese) {
                String pronounce = phraseListTab.select("div[class='baav']").text();
                if (!pronounce.isEmpty()) {
                    sb.append(pronounce).append("\n\n");
                }

            }

            // 翻译结果
            Elements transEl = isChinese ?
                    phraseListTab.select("div[class='trans-container'] ul p")
                    : phraseListTab.select("div[class='trans-container'] ul li");
            for (Element element : transEl) {
                sb.append(element.text()).append("\n");
            }

            if (!transEl.isEmpty()) {
                sb.append("\n");
            }

        } else {
            // 句子
            Elements sentenceEl = container.select("div[id='fanyiToggle'] p");
            if (!sentenceEl.isEmpty()) {
                sb.append(sentenceEl.get(0).text()).append("\n");
                sb.append(sentenceEl.get(1).text()).append("\n\n");
            }
        }

        // 例句
        if (!isChinese) {
            Elements examplesEl = container.select("div[id='bilingual'] ul li");
            for (Element element : examplesEl) {
                Elements select = element.select("p");
                for (int i = 0; i < select.size() - 1; i++) {
                    sb.append(select.get(i).text()).append("\n");
                }
            }
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        try {
            String mankind = translate("The sun disappeared from view");
            System.out.println(mankind);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
